<template>
    <view class="book-modal" v-if="visible" @tap.stop>
        <view class="book-overlay" @tap.stop="closeModal"></view>
        <view class="book-content" @tap.stop>
            <view class="book-header">
                <text class="book-title">{{ isEdit ? '编辑礼簿' : '新建礼簿' }}</text>
                <view class="header-right">
                    <text class="header-icon bigfont big-guanbi" @tap.stop="closeModal"></text>
                </view>
            </view>
            <view class="book-body">
                <view class="book-form-item">
                    <text class="form-label">
                        礼簿名称
                        <text class="required">*</text>
                    </text>
                    <input type="text" v-model="formData.title" class="form-input" placeholder="请输入礼簿名称" />
                </view>
                <view class="book-form-item">
                    <text class="form-label">
                        日期
                        <text class="required">*</text>
                    </text>
                    <view class="form-picker">
                        <picker mode="date" :value="formData.remark" @change="onDateChange"
                            style="width: 100%; height: 100%; display: block;">
                            <view class="picker-text">{{ formData.remark || '请选择日期' }}</view>
                        </picker>
                    </view>
                </view>
                <view class="book-form-item">
                    <text class="form-label">封面图片</text>
                    <view class="cover-options">
                        <scroll-view scroll-x class="cover-scroll">
                            <view class="cover-list">
                                <view v-for="cover in defaultCovers" :key="cover.id" class="cover-item"
                                    :class="{ active: formData.selectedCoverId === cover.id }"
                                    @tap="handleCoverClick(cover.id)">
                                    <view class="cover-preview" :style="getCoverStyle(cover)">
                                        <view class="cover-mask">
                                            <text class="cover-mask-text">点击更换封面</text>
                                        </view>
                                    </view>
                                    <text class="cover-text">{{ cover.text }}</text>
                                </view>
                                <view class="cover-item upload">
                                    <view class="cover-preview" @tap="chooseCover">
                                        <view class="upload-icon">+</view>
                                        <text class="upload-text">自定义</text>
                                    </view>
                                </view>
                            </view>
                        </scroll-view>
                    </view>
                </view>
            </view>
            <view class="book-footer">
                <view class="book-btn cancel" @tap="closeModal">取消</view>
                <view class="book-btn confirm" @tap="saveBook">确定</view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { createGiftBook, updateGiftBook } from '@/api/giftBook';
import { chooseAndUploadImage } from '@/utils/upload';
import { onMounted, ref, watch } from 'vue';

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    isEdit: {
        type: Boolean,
        default: false
    },
    initialData: {
        type: Object,
        default: () => ({})
    }
});

const emit = defineEmits(['update:visible', 'saved']);

// 初始化默认数据
const defaultFormData = {
    id: '',
    title: '',
    remark: '',
    coverImageUrl: '',
    type: '',
    selectedCoverId: null
};

const formData = ref({ ...defaultFormData });

// 监听visible的变化
watch(() => props.visible, (newVal) => {
    if (!newVal) {
        // 关闭时重置所有数据到初始状态
        formData.value = { ...defaultFormData };
    } else if (props.isEdit && props.initialData) {
        // 编辑模式下，设置初始数据
        formData.value = { ...props.initialData };

        // 如果是编辑模式，根据 type 找到对应的封面 ID
        if (props.initialData.type) {
            const cover = defaultCovers.value.find(c => c.type_value === props.initialData.type);
            if (cover) {
                formData.value.selectedCoverId = cover.id;
                if (!formData.value.coverImageUrl) {
                    formData.value.coverImageUrl = cover.cover;
                }
            }
        }
    } else {
        // 新建模式下，设置默认日期
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        formData.value = {
            ...defaultFormData,
            remark: `${year}-${month}-${day}`
        };
    }
}, { immediate: true });

// 默认封面数据
const defaultCovers = ref([
    {
        id: 1,
        type: 'image',
        cover: 'https://ai-public.mastergo.com/ai/img_res/4bc6e0954d08457e961ac7f7a5dbeb76.jpg',
        text: '满月酒',
        type_value: 'full_moon_party'
    },
    {
        id: 2,
        type: 'image',
        cover: 'https://ai-public.mastergo.com/ai/img_res/4ae8e25fa8628f8632f38b3b0ed816d2.jpg',
        text: '生日宴',
        type_value: 'birthday_party'
    },
    {
        id: 3,
        type: 'image',
        cover: 'https://ai-public.mastergo.com/ai/img_res/8c5164242859d8412f2368691707e4fd.jpg',
        text: '婚礼',
        type_value: 'wedding'
    },
    {
        id: 4,
        type: 'image',
        cover: 'https://ai-public.mastergo.com/ai/img_res/1305c6599ca80f3b7c2f0d3747297a70.jpg',
        text: '乔迁',
        type_value: 'house_warming'
    },
    {
        id: 5,
        type: 'image',
        cover: 'https://ai-public.mastergo.com/ai/img_res/f37135de135cff1b393609999ee5ba34.jpg',
        text: '白事',
        type_value: 'funeral'
    }
]);

// 选择封面
const selectCover = (coverId) => {
    const selectedCover = defaultCovers.value.find(c => c.id === coverId);
    if (selectedCover) {
        formData.value.coverImageUrl = selectedCover.cover;
        formData.value.type = selectedCover.type_value;
        formData.value.selectedCoverId = coverId;
    }
};

// 处理封面点击
const handleCoverClick = async (coverId) => {
    const selectedCover = defaultCovers.value.find(c => c.id === coverId);
    if (selectedCover) {
        if (formData.value.selectedCoverId === coverId) {
            try {
                const url = await chooseAndUploadImage({});
                formData.value.coverImageUrl = url;
                uni.showToast({
                    title: '更换成功',
                    icon: 'success'
                });
            } catch (error) {
                uni.showToast({
                    title: error.message || '上传失败',
                    icon: 'none'
                });
            }
        } else {
            selectCover(coverId);
        }
    }
};

// 选择自定义封面
const chooseCover = async () => {
    try {
        const url = await chooseAndUploadImage({});
        formData.value.coverImageUrl = url;
        formData.value.type = 'other';
        formData.value.selectedCoverId = null;
        uni.showToast({
            title: '上传成功',
            icon: 'success'
        });
    } catch (error) {
        uni.showToast({
            title: error.message || '上传失败',
            icon: 'none'
        });
    }
};

// 获取封面样式
const getCoverStyle = (cover) => {
    const style = {
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    };

    if (formData.value.selectedCoverId === cover.id && formData.value.coverImageUrl !== cover.cover) {
        style.backgroundImage = `url(${formData.value.coverImageUrl})`;
    } else {
        style.backgroundImage = `url(${cover.cover})`;
    }

    return style;
};

// 日期选择
const onDateChange = (e) => {
    formData.value.remark = e.detail.value;
};

// 保存礼簿
const saveBook = async () => {
    if (!formData.value.title) {
        uni.showToast({
            title: '请输入礼簿名称',
            icon: 'none'
        });
        return;
    }
    if (!formData.value.remark) {
        uni.showToast({
            title: '请选择日期',
            icon: 'none'
        });
        return;
    }
    if (!formData.value.coverImageUrl) {
        uni.showToast({
            title: '请选择封面图片',
            icon: 'none'
        });
        return;
    }

    try {
        let res;
        if (props.isEdit) {
            res = await updateGiftBook(formData.value);
        } else {
            formData.value.userId = uni.getStorageSync('token');
            res = await createGiftBook(formData.value);
        }

        if (res.code === 200) {
            uni.showToast({
                title: props.isEdit ? '修改成功' : '创建成功',
                icon: 'success',
                duration: 2000
            });
            // 重置数据到初始状态
            formData.value = { ...defaultFormData };
            closeModal();
            emit('saved');
        } else {
            uni.showToast({
                title: res.msg || (props.isEdit ? '修改失败' : '创建失败'),
                icon: 'none'
            });
        }
    } catch (error) {
        uni.showToast({
            title: error.message || (props.isEdit ? '修改失败' : '创建失败'),
            icon: 'none'
        });
    }
};

// 关闭弹窗
const closeModal = () => {
    // 重置数据到初始状态
    formData.value = { ...defaultFormData };
    // 通知父组件更新visible
    emit('update:visible', false);
};

// 在组件挂载时添加日志
onMounted(() => {
    console.log('BookModal mounted, visible:', props.visible);
});
</script>

<style scoped>
.book-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.book-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
}

.book-content {
    position: relative;
    width: 90%;
    max-width: 800rpx;
    background: var(--theme-card);
    border-radius: 24rpx;
    overflow: hidden;
    padding-bottom: 0;
    animation: scaleIn 0.3s ease;
    z-index: 100000;
}

.book-header {
    padding: 36rpx 40rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid var(--theme-primary-border);
}

.book-title {
    font-size: 32rpx;
    font-weight: 600;
    color: var(--theme-text);
}

.header-right {
    display: flex;
    align-items: center;
}

.header-icon {
    font-size: 40rpx;
    color: var(--theme-text-light);
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: -20rpx;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.header-icon:active {
    background: rgba(0, 0, 0, 0.05);
    transform: scale(0.95);
}

.book-body {
    padding: 40rpx;
    max-height: 800rpx;
    overflow-y: auto;
}

.book-form-item {
    margin-bottom: 24rpx;
}

.form-label {
    font-size: 28rpx;
    color: var(--theme-text);
    margin-bottom: 12rpx;
    display: block;
}

.required {
    color: #FF4D4F;
    margin-left: 4rpx;
}

.form-input {
    width: 100%;
    height: 80rpx;
    background: rgba(91, 158, 231, 0.04);
    border-radius: 12rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: var(--theme-text);
    border: 2rpx solid transparent;
    box-sizing: border-box;
}

.form-input:focus {
    border-color: var(--theme-primary);
    background: rgba(91, 158, 231, 0.08);
}

.form-picker {
    width: 100%;
    height: 80rpx;
    background: rgba(91, 158, 231, 0.04);
    border-radius: 12rpx;
    border: 2rpx solid transparent;
    overflow: hidden;
}

.picker-text {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: var(--theme-text);
}

.book-footer {
    padding: 32rpx 40rpx;
    padding-bottom: 32rpx;
    border-top: 1rpx solid var(--theme-primary-border);
    display: flex;
    gap: 20rpx;
}

.book-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;
}

.book-btn.cancel {
    background: var(--theme-background);
    color: var(--theme-text);
    border: 2rpx solid var(--theme-primary-border);
}

.book-btn.confirm {
    background: var(--theme-gradient);
    color: #FFFFFF;
}

.book-btn:active {
    opacity: 0.9;
    transform: scale(0.98);
}

@keyframes scaleIn {
    from {
        transform: scale(0.8);
        opacity: 0;
    }

    to {
        transform: scale(1);
        opacity: 1;
    }
}

/* 保持原有的封面选择相关样式 */
.cover-options {
    margin-top: 12rpx;
}

.cover-scroll {
    width: 100%;
    white-space: nowrap;
}

.cover-list {
    display: inline-flex;
    padding: 12rpx 4rpx;
    gap: 20rpx;
}

.cover-item {
    width: 160rpx;
    height: 200rpx;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
}

.cover-preview {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    overflow: hidden;
    border: 4rpx solid transparent;
    box-sizing: border-box;
    transition: all 0.3s ease;
    background-size: cover;
    background-position: center;
}

.cover-item.active .cover-preview {
    border-color: var(--theme-primary);
    box-shadow: 0 8rpx 16rpx rgba(64, 128, 255, 0.2);
}

.cover-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: all 0.3s ease;
}

.cover-item.active .cover-mask {
    opacity: 1;
}

.cover-mask-text {
    color: #FFFFFF;
    font-size: 24rpx;
    text-align: center;
}

.cover-text {
    font-size: 24rpx;
    color: var(--theme-text);
    text-align: center;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.cover-item.active .cover-text {
    color: var(--theme-primary);
    font-weight: 500;
}

.cover-item.upload .cover-preview {
    background: rgba(91, 158, 231, 0.04);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2rpx dashed rgba(91, 158, 231, 0.3);
}

.upload-icon {
    font-size: 48rpx;
    color: var(--theme-primary);
    margin-bottom: 8rpx;
}

.upload-text {
    font-size: 24rpx;
    color: var(--theme-text-secondary);
}

/* 暗黑模式适配 */
.dark-mode .book-content {
    background: var(--theme-card);
}

.dark-mode .form-input {
    background: rgba(255, 255, 255, 0.04);
}

.dark-mode .form-input:focus {
    background: rgba(255, 255, 255, 0.08);
}

.dark-mode .form-picker {
    background: rgba(255, 255, 255, 0.04);
}

.dark-mode .cover-item.upload .cover-preview {
    background: rgba(255, 255, 255, 0.04);
    border-color: rgba(255, 255, 255, 0.2);
}
</style>